package com.supsi.segretaria.server;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/*
 * User: Fabio Mastromatteo
 * Date: 30.03.12 - 07.06.12
 */

/**
 * ConnectionThread: handles the communication with the client.
 * Instantiates a MessageInterpreter class that keeps the communication state and talks with the MailSystem.
 */
public class ConnectionThread extends Thread{
    private Socket s;                  // Client socket
    protected boolean closed = false;  // connection state
    private MessageInterpreter messageInterpreter = new MessageInterpreter(this);

    public ConnectionThread(Socket s) {
        this.s = s;
    }

    public void run(){
        String clientSentence;
        try {
            while(!closed){
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                DataOutputStream out = new DataOutputStream(s.getOutputStream());
                clientSentence = in.readLine();
                System.out.println(clientSentence);
                if (clientSentence.equalsIgnoreCase("EXIT")){
                    out.writeBytes("BYE BYE\n");
                    System.out.println("Client disconnected");
                    s.close();
                    closed=true;
                    messageInterpreter.close();
                } else {
                    out.writeBytes(messageInterpreter.inter(clientSentence));
                }
            }
        }
        catch (IOException e1){
            messageInterpreter.connectionLost();
        }
        catch (NullPointerException e2){
            messageInterpreter.connectionLost();
        }
    }

    /**
     * New message notification
     */
    public void notifyNewMessage(){
        try {
            DataOutputStream out = new DataOutputStream(s.getOutputStream());
            out.writeBytes("NOTIFY\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
